package chapter05.testbundlelistener;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;
import org.osgi.framework.BundleEvent;
import org.osgi.framework.BundleListener;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.FrameworkListener;

public class Activator implements BundleActivator, BundleListener, FrameworkListener {

	@Override
	public void start(BundleContext context) throws Exception {
		context.addBundleListener(this);
		context.addFrameworkListener(this);
	}
	
	@Override
	public void stop(BundleContext context) throws Exception {
		context.removeBundleListener(this);
		context.removeFrameworkListener(this);
	}

	@Override
	public void bundleChanged(BundleEvent event) {
		System.out.println("Bundle [" + event.getBundle().getSymbolicName() + "] " + getBDStateName(event.getType()));
	}
	
	@Override
	public void frameworkEvent(FrameworkEvent event) {
		System.out.println("FrameworkEvent " + getFWStateName(event.getType()));
		
	}

	private String getBDStateName(int state){
		switch (state) {
		case BundleEvent.INSTALLED:
			return "INSTALLED";
		case BundleEvent.STARTED:
			return "Installed";
		case BundleEvent.STOPPED:
			return "STOPPED";
		case BundleEvent.UPDATED:
			return "UPDATED";
		case BundleEvent.UNINSTALLED:
			return "UNINSTALLED";
		case BundleEvent.RESOLVED:
			return "RESOLVED";
		case BundleEvent.UNRESOLVED:
			return "UNRESOLVED";
		case BundleEvent.STARTING:
			return "STARTING";
		case BundleEvent.STOPPING:
			return "STOPPING";
		default:
			return Integer.toHexString(state);
		}
	}
	
	private String getFWStateName(int state){
		switch (state) {
		case FrameworkEvent.STARTED:
			return "STARTED";
		case FrameworkEvent.ERROR:
			return "ERROR";
		case FrameworkEvent.PACKAGES_REFRESHED:
			return "PACKAGES_REFRESHED";
		case FrameworkEvent.STARTLEVEL_CHANGED:
			return "STARTLEVEL_CHANGED";
		case FrameworkEvent.WARNING:
			return "WARNING";
		default:
			return Integer.toHexString(state);
		}
	}

}
